﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using SharpTeam.Crm.SkypeDialer.Configuration.crmdiscovery;

namespace SharpTeam.Crm.SkypeDialer.Configuration
{
    public class CrmConnection
    {
        public static void CheckDiscoveryService(string serverUrl, System.Net.ICredentials credentials)
        {
            CrmDiscoveryService service = GetDiscoveryService(credentials, serverUrl);

            RetrieveOrganizationsRequest req = new RetrieveOrganizationsRequest();

            RetrieveOrganizationsResponse resp = (RetrieveOrganizationsResponse)service.Execute(req);
        }

        internal static CrmDiscoveryService GetDiscoveryService(ICredentials credentials, string serverUrl)
        {
            return new CrmDiscoveryService
                       {
                           Credentials = credentials,
                           Url =
                               string.Format(
                                   "{0}/mscrmservices/2007/ad/crmdiscoveryservice.asmx?WSDL",
                                   serverUrl)
                       };
        }

        public static string[] GetOrganizations(ICredentials credentials, string serverUrl)
        {
            CrmDiscoveryService service = GetDiscoveryService(credentials, serverUrl);

            RetrieveOrganizationsRequest req = new RetrieveOrganizationsRequest();

            RetrieveOrganizationsResponse resp = (RetrieveOrganizationsResponse)service.Execute(req);

            return (from od in resp.OrganizationDetails
                    select od.OrganizationName).ToArray();
        }
    }
}
